<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends CI_Controller {
	
	var $per_product;

	public function __construct()
	{
		parent::__construct();

		$this->template->set('nav', $this->uri->segment(1));
		$this->template->set('title', 'Vietnam T-shirts Shop');
		$this->template->set('section', 'Vietnam T-shirts Shop');	

		// load model
		$this->load->model('Product_model');
		$this->load->model('User_model');
		$this->load->model('Product_images_model');
		$this->load->model('Product_sizes_model');
		$this->load->model('Article_model');

		// orders
		$this->load->model('Order_model');
		$this->load->model('Order_sizes_model');

		// load model kho
		$this->load->model('Storage_model');	
		// load model history kho
		$this->load->model('Storage_product_history_model');
		// load products that in storage
		$this->load->model('Storage_product_model');		
		// load model code_export_form
		$this->load->model('Code_export_form_model');
		// load model export temporary
		$this->load->model('Code_export_form_tmp_model');
		// 
		$this->load->model('Export_form_model');
		// category
		$this->load->model('Category_model');

		$this->load->library('cart');

		// defined product per page
		$this->per_product = 12;

		$this->load->library('parser');

		//
		$this->db->save_queries = FALSE;
	}

	public function index()
	{
		$data['web_title']  = 'Vietnam T-shirts Shop';	

		$start = $this->uri->segment(2);		

		if(empty($start))
			$start = 1;

		$start = ($start - 1) * $this->per_product;

		$limit = $this->per_product;		

		// list all categories
		$categories = $this->Category_model->getRecords();

		foreach ($categories as $cat) 
		{
			$data['categories'][] = array(
					'category_id'		=>	$cat->id,
					'category'			=>	$cat->title,
				);
		}

		/////////// search /////////////////////////////////////////
		$search = array();

		$category_id = '';
		if($this->input->post('category'))
		{
			$category_id = $this->input->post('category');
			$search['category_id'] = $category_id;			
		}		
		if($this->input->post('order'))
		{
			$order = $this->input->post('order');

			$search['order'] = $order;
		}

		////////////////////////////////////////////////////////////

		// list all new products
		$products = $this->Product_model->loadAllV3($start, $limit, $search);		
		$data['products'] = $products['data'];
		$data['homepage'] = site_url();

		// total cart
		$data['total_cart'] = $this->cart->total_items();

		$list_products = array();
		// list all product with desginer info		
		foreach ($data['products'] as $product) 
		{
			$designer = $this->User_model->getUser($product->user_id);			

			$list_products[] = array(
					'id'			=>	$product->id,
					'title'			=>	$product->title,
					'color'			=>	$product->color,
					'slug'			=>	$product->slug,
					'image'			=>	!empty($product->image) ? base_url('uploads/image/products/'.$product->image) : 'http://placehold.it/182x250',
					'designer'		=>	!empty($designer->fullname) ? $designer->fullname : '',
					'designer_slug'	=>	!empty($designer->slug) ? $designer->slug : '',
					'desginer_id'	=>	!empty($designer->id) ? $designer->id : '',
					// for fast
					'product_link'	=>	site_url('ao-thun/'.$product->slug.'_'.$product->id),
				);			
		}
		$data['list_products'] = $list_products;		

		$this->load->helper('url');
		$this->load->library('pagination');    	

	    ////////////////// pagination //////////////////////////////////////
		$this->load->library('pagination');

		$config['base_url']   = site_url('page');
		$config['total_rows'] = $products['count'];
		$config['per_page'] = $limit;
		$config['uri_segment'] = 2;
		$config['use_page_numbers'] = TRUE;
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		// first link
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		// next link
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';	
		// previous link
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		// end link
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		// current
		$config['cur_tag_open'] = '<li class="active"><a href="#">';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
		// digit link
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$this->pagination->initialize($config); 

		$data['pagination'] = $this->pagination->create_links();

		////////////////////////////////////////////////////////////////////

		if($this->input->post('ajax'))
		{						
			$this->parser->parse('homepage/index_products',$data);
		}
		else
		{			
			$this->parser->parse('homepage/index',$data);
		}		
	}

	public function product($slug = false)
	{
		if(empty($slug))
		{
			redirect('home');
		}		

		// analyze slug		
		$slug_analyze = explode("_", $slug);		

		// get last element (should be id)
		$product_id = end($slug_analyze);			

		// get slug 
		$product_slug = $slug_analyze[0];		

		$session_cart = $this->session->userdata('session_cart');		

		// if product id is not numeric, then not product
		//if(!is_numeric($product_id))
		{
			// check slug and show list of products with that slug			
			$products = $this->Product_model->showListOfProducts($product_slug);

			$list_products = array();
			foreach ($products as $product) 
			{
				if(!empty($product->color_code))
				{					
					$designer = $this->User_model->getUser($product->user_id);

					$product_images = $this->Product_images_model->infos(array('product_id'=>$product->id));

					$product_sizes = $this->Product_sizes_model->getInfoSizeProduct($product->id);

					$xs = $s = $m = $l = $xl = $xxl = $xxxl = '';
					
					foreach ($product_sizes as $obj) 
					{
						$product_size = $obj->size;

						switch ($product_size) 
						{
							case 'xs':
								$xs = $obj->quantity;
								break;
							case 's':
								$s = $obj->quantity;
								break;
							case 'm':
								$m = $obj->quantity;
								break;
							case 'l':
								$l = $obj->quantity;
								break;
							case 'xl':
								$xl = $obj->quantity;
								break;
							case 'xxl':
								$xxl = $obj->quantity;
								break;
							case 'xxxl':
								$xxxl = $obj->quantity;
								break;

							default:
								# code...
								break;
						}
					}				

					$list_products[] = array(
							'lcolor'				=>	$product->color_code,
							'lproduct_link'			=>	site_url('ao-thun/'.$product->slug.'_'.$product->id),
							// 'title'				=>	$product->title,
							// 'code'				=>	$product->code,
							// 'color'				=>	$product->color,
							// 'slug'				=>	$product->slug,
							// 'image'				=>	$product->image,	// main image
							// // designer info 
							// 'designer'			=>	$designer->fullname,	// full name
							// 'designer_img'		=>	$designer->image,		//image
							// 'designer_desc'		=>	$designer->desc,		//designer description
							// // product images
							// 'product_images'	=>	$product_images,
							// // product sizes
							// 'xs'				=>	$xs,
							// 's'					=>	$s,
							// 'm'					=>	$m,
							// 'l'					=>	$l,
							// 'xl'				=>	$xl,
							// 'xxl'				=>	$xxl,
							// 'xxxl'				=>	$xxxl,
						);
				}
			}

			// if(!empty($list_products))
			// {
			// 	$data['products'] = $list_products;
			// 	$this->template->load_homepage('home/template','home/products',$data);
			// }
			// else
			// {
			// 	redirect('home');
			// }
		}


		//else
		{			
			// get product
			$product = $this->Product_model->showListOfProducts($product_slug, $product_id);				

			// get related product
			$related_products = $this->Product_model->showListOfRelatedProducts($product->category_id,$product->id);

			$related_products_1 = array();

			foreach ($related_products as $rproduct) 
			{
				$designer = $this->User_model->getUser($rproduct->user_id);	

				$related_products_1[] = array(
						'rproduct'		=>	$rproduct->title,
						'rimage'			=>	!empty($rproduct->image) ? base_url('uploads/image/products/'.$rproduct->image) : 'http://placehold.it/220x250',	
						'rslug'			=>	$rproduct->slug,
						'rproduct_link'	=>	site_url('ao-thun/'.$rproduct->slug.'_'.$rproduct->id),
						'rdesigner'		=>	!empty($designer->fullname) ? $designer->fullname : '',
					);
			}			

			// get full info for product
			$fullInfoProduct = array();

			$designer = $this->User_model->getUser($product->user_id);

			$product_images = $this->Product_images_model->infos(array('product_id'=>$product->id));

			$product_sizes = $this->Product_sizes_model->getInfoSizeProduct($product->id);

			$xs = $s = $m = $l = $xl = $xxl = $xxxl = '';

			// get article
			$article = $this->Article_model->info1($product->id);
				
			foreach ($product_sizes as $obj) 
			{
				$product_size = $obj->size;

				switch ($product_size) 
				{
					case 'xs':
						$xs = $obj->quantity;
						break;
					case 's':
						$s = $obj->quantity;
						break;
					case 'm':
						$m = $obj->quantity;
						break;
					case 'l':
						$l = $obj->quantity;
						break;
					case 'xl':
						$xl = $obj->quantity;
						break;
					case 'xxl':
						$xxl = $obj->quantity;
						break;
					case 'xxxl':
						$xxxl = $obj->quantity;
						break;

					default:
						# code...
						break;
				}
			}				

			$product_price = $product->price;

			$product_imagesinfo = array();
			foreach ($product_images as $product_image) 
			{
				$product_imagesinfo[] = array(
						'image1'	=>	!empty($product_image->image) ? base_url('uploads/image/products/'.$product_image->image) : 'http://placehold.it/620x390',
					);
			}			

			$fullInfoProduct = array(
					'homepage'			=>	site_url(),
					'id'				=>	$product->id,
					'title'				=>	$product->title,
					'price'				=>	$product_price,
					'pricek'			=>	str_replace('000', 'k', $product_price),
					'code'				=>	$product->code,
					'color'				=>	$product->color,
					'slug'				=>	$product->slug,
					'image'				=>	$product->image,	// main image
					// designer info 
					'designer'			=>	!empty($designer->fullname) ? $designer->fullname : "",	// full name
					'designer_img'		=>	!empty($designer->image) ? base_url('uploads/image/designer/'.$designer->image) : base_url('utils/img/avatar.jpeg'),		//image
					'designer_desc'		=>	!empty($designer->desc) ? $designer->desc : "",		//designer description
					'designer_website'	=>	!empty($designer->website) ? $designer->website : "",		//designer description
					// product images
					'product_images'	=>	$product_imagesinfo,
					// product sizes
					'xs'				=>	($xs > 0) ? '<li id="xs"><a href="#" class="gray-btn"><b>XS</b><span>còn '.$xs.'</span></a></li>' : '',
					's'					=>	($s > 0) ? '<li id="s"><a href="#" class="gray-btn"><b>S</b><span>còn '.$s.'</span></a></li>' : '',
					'm'					=>	($m > 0) ? '<li id="m"><a href="#" class="gray-btn"><b>M</b><span>còn '.$m.'</span></a></li>' : '',
					'l'					=>	($l > 0) ? '<li id="l"><a href="#" class="gray-btn"><b>L</b><span>còn '.$l.'</span></a></li>' : '',
					'xl'				=>	($xl > 0) ? '<li id="xl"><a href="#" class="gray-btn"><b>XL</b><span>còn '.$xl.'</span></a></li>' : '',
					'xxl'				=>	($xxl > 0) ? '<li id="xxl"><a href="#" class="gray-btn"><b>2XL</b><span>còn '.$xxl.'</span></a></li>' : '',
					'xxxl'				=>	($xxxl > 0) ? '<li id="xxxl"><a href="#" class="gray-btn"><b>3XL</b><span>còn '.$xxxl.'</span></a></li>' : '',
					// article
					'article_image'		=>	!empty($article->image) ? base_url('uploads/image/products/'.$article->image) : base_url('utils/img/1.jpg'),
					'article_title'		=>	!empty($article->title) ? $article->title : "",
					'article_detail'	=>	!empty($article->detail) ? $article->detail : "",
					'related_products'	=>	$related_products_1,
					// list product
					'list_products'		=>	$list_products,
					// cart
					'total_cart'		=>	$this->cart->total_items(),
					// add cart
					'add_to_cart'		=>	site_url('home/addCart/'.$product->id),
					'addCart'			=>	site_url('home/cart'),
				);	

			if(empty($xs) && empty($s) && empty($m) && empty($l) && empty($xl) && empty($xxl) && empty($xxxl))							
			{
				$fullInfoProduct['na'] = true;
			}
			
			$fullInfoProduct['emptyproducts'] = 'no';
			if(empty($list_products))
			{
				$fullInfoProduct['emptyproducts'] = 'yes';
			}

			if(!empty($fullInfoProduct))
			{
				$data = $fullInfoProduct;
				$this->parser->parse('homepage/product',$data);
			}
			else
			{
				redirect('home');
			}
		}

		//redirect('home'); // since we couldn't find this product, should back to home
	}

	public function addToCart($product_id,$size)
	{
		$product = $this->Product_model->getEntry($product_id);

		$session_cart = $this->session->userdata('session_cart');

		if(!empty($session_cart))
		{
			$new_session = array(
							'id'		=>	$product->id,
							'qty'		=>	1,
							'price'		=>	$product->price,
							'name'		=>	$product->slug,
							'options'	=>	array('Size' => $size,'Product' => $product),
						);
			array_push($session_cart, $new_session);
		}		
		else
		{
			$session_cart = array(
						array(
							'id'		=>	$product->id,
							'qty'		=>	1,
							'price'		=>	$product->price,
							'name'		=>	$product->slug,
							'options'	=>	array('Size' => $size,'Product' => $product),
						)
					);								
		}

		$this->session->set_userdata('session_cart', $session_cart);


		redirect('ao-thun/'.$product->slug.'_'.$product->id);
	}

	public function total_cart()
	{
		echo $this->cart->total_items();
	}

	public function addCart($now = false)
	{		
		$product_id = $this->input->post('id');

		$product = $this->Product_model->getEntry($product_id);

		$xs = $s = $m = $l = $xl = $xxl = $xxxl = '';

		// 
		$xs = $this->input->post('xs');
		$s = $this->input->post('s');
		$m = $this->input->post('m');
		$l = $this->input->post('l');
		$xl = $this->input->post('xl');
		$xxl = $this->input->post('xxl');
		$xxxl = $this->input->post('xxxl');

		//
		$xs = !empty($xs) ? $xs : 0;
		$s = !empty($s) ? $s : 0;
		$m = !empty($m) ? $m : 0;
		$l = !empty($l) ? $l : 0;
		$xl = !empty($xl) ? $xl : 0;
		$xxl = !empty($xxl) ? $xxl : 0;
		$xxxl = !empty($xxxl) ? $xxxl : 0;
		
		if($xs > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$xs,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'XS','Product' => $product),
					);

			$this->cart->insert($data);
		}
		if($s > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$s,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'S','Product' => $product),
					);
			$this->cart->insert($data);
		}
		if($m > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$m,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'M','Product' => $product),
					);

			$this->cart->insert($data);
		}
		if($l > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$l,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'L','Product' => $product),
					);
			$this->cart->insert($data);
		}
		if($xl > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$xl,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'XL','Product' => $product),
					);
			$this->cart->insert($data);
		}
		if($xxl > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$xxl,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'XXL','Product' => $product),
					);
			$this->cart->insert($data);
		}
		if($xxxl > 0)
		{
			$data = array(
						'id'		=>	$product->id,
						'qty'		=>	$xxxl,
						'price'		=>	$product->price,
						'name'		=>	$product->slug,
						'options'	=>	array('Size' => 'XXXL','Product' => $product),
					);
			$this->cart->insert($data);
		}				

		//echo $product_id . print_r($data);
		$total_items = $this->cart->total_items();

		$total_items = intval($total_items);

		echo $total_items;
	}

	public function updateCart()
	{
		$data = $_POST;		

		$this->cart->update($data); 		

		redirect('home/cart');
	}

	public function cart()
	{	
		// echo "<pre>";
		// print_r($this->cart->contents());
		// echo "</pre>";
		//$this->template->load_homepage('home/template','home/cart');

		$this->load->view('homepage/cart');
	}

	public function destroycart()
	{
		$this->cart->destroy();
	}

	public function info()
	{
		$this->template->load_homepage('home/template', 'home/info');
	}

	public function confirm()
	{
		if(!empty($_POST))
		{
			$fullname = $this->input->post('fullname');
			$phone = $this->input->post('phone');
			$email = $this->input->post('email');
			$city = $this->input->post('city');
			$address = $this->input->post('address');		
			
		}		
		
		// get items
		$items = $this->cart->contents();	
		$items_cart = $items;				

		//////////////// create order sizes ////////////////

		foreach ($items as $item) 
		{
			$product = $item['options']['Product'];

			$product_id = $product->id;
			$product_code = $product->code;
			$price = $product->price;
			$product_name = $product->title;
			$product_color = $product->color;	

			$option_value = $this->cart->product_options($item['rowid']); 
			$size = $option_value['Size'];

			//////////////// create order /////////////////////			
			$data = array(
						'customer_name'		=>	$fullname,
						'customer_phone'	=>	$phone,
						'shipping_address'	=>	$address,
						'product_id'		=>	$product_id,
				);

			$this->Order_model->insert($data);		

			// get last insert id
			$order_id = $this->db->insert_id();

			///////////////// order sizes ///////////////////
			$product_id = $item['id'];			
			$size = $item['options']['Size'];
			$quantity = $item['qty'];

			if(is_numeric($quantity) && $quantity > 0)
			{
				$data = array(
						'order_id'		=>	$order_id,
						'product_id'	=>	$product_id,
						'size'			=>	$size,
						'quantity'		=>	$quantity,
					);

				// create order size
				$this->Order_sizes_model->insert($data);
				//echo $this->db->last_query();
			}

			//////////////// remove //////////////////////////
			$product_codei = $this->returnCode($product_code, $size);			

			$cond1['product_code'] = $product_codei;

			$itemwithSize = $this->Storage_product_model->loadAllV5($quantity,0,$cond1);

			$itemsizes = $itemwithSize['data'];			

			foreach ($itemsizes as $i) 
			{
				$id = $i->id;
				$storage_id = $i->storage_id;
				// $data = array('active' => 0);	

				//$this->Storage_product_model->updateEntry($data,$id);

				$this->process($id, $storage_id, $order_id, false);
			}
			///////////////////////////////////////////////////	
		}

		$data['itemss']	= $items_cart;

		$data['total_cart'] = $this->cart->total();

		// destroy cart
		$this->cart->destroy();

		// grant data
		$data['fullname'] = $fullname;
		$data['phone'] = $phone;
		$data['email'] = $email;
		$data['city'] = $city;
		$data['address'] = $address;



		// load page confirm
		$this->template->load_homepage('home/template', 'home/confirm', $data);
	}	


	// export
	public function process($id,$storage_id,$order_id,$redirect = true)
	{				
		// get code from storage_product
		$storage_product = $this->Storage_product_model->getEntry('id', $id);		
		$product_id = $storage_product->product_id;
		$product = $this->Product_model->getEntry($product_id);
		$code = $storage_product->product_code;
		$storage_info = $this->Storage_model->getEntry($storage_product->storage_id);
		$storage_title = $storage_info->title;		
		$product_size = $this->Product_sizes_model->getEntry('code',$code);

		// create record in code_export_form
		$data = array(
				'code'					=>	$code,
				'storage'				=>	$storage_title,
				'order_id'				=>	$order_id,
				'storage_product_id'	=>	$storage_product->id,
				'active'				=>	1,
			);
		$codeport_insertId = $this->Code_export_form_model->insert($data);

		// remove code from storage_product
		$this->Storage_product_model->remove($id);	

		// remove quantity from product_sizes
		$this->Product_sizes_model->updateQuantity($code,'decrease');	

		// increase quantity of store
		$this->Storage_model->updateQuantity($storage_id,'increase');

		// log history		
		$data = array(
				'product'		=>	$product->title,
				'product_id'	=>	$product->id,
				'size'			=>	$product_size->size,
				'code'			=>	$code,
				'storage_id'	=>	$storage_info->id,
				'storage'		=>	$storage_title,
				'type'			=>	2,			
			);
		$history_id = $this->Storage_product_history_model->insertHistory($data);

		// update history id to code_export_form
		$data = array('history_id' => $history_id);

		$this->Code_export_form_model->update($data, $codeport_insertId);	

		$previous_url = $this->session->userdata('currentURL');

		if(empty($previous_url))
			$previous_url = 'exportw/index';
		// return to index
		if($redirect)
			redirect($previous_url);
	}	

	public function news($slug = false)
	{
		$this->load->model('New_model');		

		$data['new'] = $this->New_model->info_slug($slug);
		$data['categories'] = $this->Category_model->getRecords();

		$this->template->set('title', $data['new']->title);

		$this->template->load('home/template','home/news',$data);
	}


	function returnCode($product_code, $size)
	{
		$size = strtoupper($size);

		switch ($size) {
			case 'XS':
				return $product_code.'1';
				break;
			case 'S':
				return $product_code.'2';
				break;
			case 'M':
				return $product_code.'3';
				break;
			case 'L':
				return $product_code.'4';
				break;
			case 'XL':
				return $product_code.'5';
				break;
			case 'XXL':
				return $product_code.'6';
				break;
			case 'XXXL':
				return $product_code.'7';
				break;				
			default:
				# code...
				break;
		}
	}	
}	